<template>
  <div class="login-container">
    <div class="login-box">
      <div class="leftBox"></div>
      <div
        v-loading="socialLoginLoading"
        element-loading-text="第三方账号登入中..."
        class="rightBox"
      >
        <div class="logoBox">
          <img
            class="logo"
            src="favicon.ico"
          >
          <span>Lazypg Admin</span>
        </div>
        <p class="tipText">
          欢 迎 回 来 ！ 请 登 录 您 的 账 号
        </p>
        <el-form
          ref="loginForm"
          class="formBox"
          :model="loginForm"
          :rules="loginRules"
        >
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              type="text"
              tabindex="1"
              size="medium"
              autocomplete="on"
              class="input"
              placeholder="请 输 入 账 号"
            >
              <span
                slot="prefix"
                class="inputLabel"
              >
                账 号
              </span>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              ref="password"
              v-model="loginForm.password"
              size="medium"
              class="input"
              placeholder="请 输 入 密 码"
              :type="passwordType"
              name="password"
              tabindex="2"
              autocomplete="on"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            >
              <span
                slot="prefix"
                class="inputLabel"
              >
                密 码
              </span>
              <span
                slot="suffix"
                class="show-pwd"
                @click="showPwd"
              >
                <svg-icon
                  :name="passwordType === 'password' ? 'eye-off' : 'eye-on'"
                ></svg-icon>
              </span>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="rememberBox">
          <div class="checkBox">
            <el-checkbox v-model="isRemeber">
              记住密码
            </el-checkbox>
          </div>
          <!-- <span class="forgetPWS">忘记密码</span> -->
        </div>
        <div class="btnBox">
          <!-- <el-button
            size="medium"
            class="btn"
            type="success"
            @click="openUrl('https://test.hivemarket.club/#/dashboard')"
          >
            Hive Scrm登入
          </el-button> -->
          <el-button
            size="medium"
            type="primary"
            class="btn"
            :loading="loading"
            @click.native.prevent="handleLogin"
          >
            登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { Route } from 'vue-router'
import { Dictionary } from 'vue-router/types/router'
import { Form as ElForm, Input } from 'element-ui'
import { UserModule } from '@/store/modules/user'
import { bindSocialAccount } from '@/api/user.ts'
import { openUrl } from '@/utils'
import { log } from 'console'

@Component({
  name: 'Login',
  components: {}
})
export default class extends Vue {
  private validateUsername = (rule: any, value: string, callback: Function) => {
    if (!value) {
      callback(new Error('请输入正确的用户名'))
    } else {
      callback()
    }
  }

  created() {
    // 记住密码 回显
    const userName = localStorage.getItem('userName')
    const password = localStorage.getItem('password')
    if (userName && password) {
      this.loginForm.username = userName
      this.loginForm.password = window.atob(password) // "test"
      this.isRemeber = true
    }
  }

  private validatePassword = (rule: any, value: string, callback: Function) => {
    if (!value) {
      callback(new Error('请输入密码'))
    } else {
      callback()
    }
  }

  private loginForm = {
    username: '',
    password: ''
  }

  private loginRules = {
    username: [{ validator: this.validateUsername, trigger: 'blur' }],
    password: [{ validator: this.validatePassword, trigger: 'blur' }]
  }

  private passwordType = 'password'
  private loading = false
  private socialLoginLoading = false
  private isRemeber = false
  private showDialog = false
  private capsTooltip = false
  private redirect?: string
  private otherQuery: Dictionary<string> = {}
  public openUrl: Function = openUrl

  @Watch('$route', { immediate: true })
  private onRouteChange(route: Route) {
    // TODO: remove the "as Dictionary<string>" hack after v4 release for vue-router
    // See https://github.com/vuejs/vue-router/pull/2050 for details
    const query = route.query as Dictionary<string>
    if (query) {
      this.redirect = query.redirect
      this.otherQuery = this.getOtherQuery(query)
    }
  }

  mounted() {
    this.handlerSocialAccountLogin()
  }

  private checkCapslock(e: KeyboardEvent) {}

  private showPwd() {
    if (this.passwordType === 'password') {
      this.passwordType = ''
    } else {
      this.passwordType = 'password'
    }
    this.$nextTick(() => {
      (this.$refs.password as Input).focus()
    })
  }

  private async handlerSocialAccountLogin() {
    if (this.$route.query.social_type && this.$route.query.u_token) {
      try {
        await UserModule.LogOut()
        this.socialLoginLoading = true
        const socialParams = {
          openId: undefined,
          socialType: this.$route.query.social_type.toString(),
          appToken: this.$route.query.app_token
            ? this.$route.query.app_token.toString()
            : '',
          userToken: this.$route.query.u_token.toString()
        }
        const resp = await bindSocialAccount(socialParams)
        socialParams.openId = resp.data
        await UserModule.SocialLogin(socialParams)
        this.$router.push('/')
      } finally {
        this.socialLoginLoading = false
      }
    }
  }

  private handleLogin() {
    (this.$refs.loginForm as ElForm).validate(async(valid: boolean) => {
      if (valid) {
        this.loading = true
        try {
          console.log('123123')
          // await UserModule.LogOut()
          await UserModule.Login(this.loginForm)
          if (this.isRemeber) {
            localStorage.setItem('userName', this.loginForm.username)
            localStorage.setItem(
              'password',
              window.btoa(this.loginForm.password)
            )
          } else {
            localStorage.removeItem('userName')
            localStorage.removeItem('password')
          }
          // this.$router.push('/').catch(() => {
          //   console.log('...')
          // })
        } catch (err) {
          this.loading = false
        }
      } else {
        return false
      }
    })
  }

  private getOtherQuery(query: Dictionary<string>) {
    return Object.keys(query).reduce((acc, cur) => {
      if (cur !== 'redirect') {
        acc[cur] = query[cur]
      }
      return acc
    }, {} as Dictionary<string>)
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__inner {
  border-top: none;
  border-left: none;
  border-right: none;
  border-radius: 0;
  padding-left: 60px;
  padding-bottom: 0px;
  font-size: 16px;
}
::v-deep .el-input__prefix {
  padding-top: 4px;
}
::v-deep .el-input__suffix {
  padding-top: 4px;
}
.login-container {
  .inputLabel {
    color: #333;
    font-weight: bold;
    font-size: 16px;
  }
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: url('~@/assets/img/loginBg.png') 100% 100% no-repeat;
  background-size: 100% 100%;

  .login-box {
    height: 580px;
    width: 880px;
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    box-shadow: 0px 0px 8px 2px rgba($color: #000000, $alpha: 0.1);
    .leftBox {
      flex: 1;
      height: 100%;
      background: url('~@/assets/img/loginLeft.png');
      background-size: 100% 580px;
    }
    .rightBox {
      flex-basis: 50%;
      height: 100%;
      background: white;
      text-align: center;
      padding: 0 60px;
      box-sizing: border-box;
      .logoBox {
        margin-top: 100px;
        font-size: 24px;
        font-weight: bold;
        .logo {
          width: 50px;
          height: 50px;
          vertical-align: -15px;
          margin-right: 8px;
        }
      }
      .tipText {
        color: #909699;
        font-size: 14px;
        margin: 20px 0 40px;
      }
      // .formBox{
      //     .input{}
      // }
      .rememberBox {
        display: flex;
        margin-top: 30px;
        .checkBox {
          flex: 1;
          text-align: left;
        }
        .forgetPWS {
          font-size: 14px;
          cursor: pointer;
          text-decoration: underline;
          color: #333;
        }
      }
      .btnBox {
        display: flex;
        margin-top: 60px;
        .btn {
          flex: 1;
        }
      }
    }
  }
}
</style>
